function varargout = ProjectConfigManager(operation, varargin)
% ProjectConfigManager - 项目配置管理业务逻辑
% 严格遵循DO-178规则：业务逻辑与GUI分离
%
% 用法:
%   configPath = ProjectConfigManager('getConfigPath')
%   categoryData = ProjectConfigManager('getCategoryData', configPath)
%   fileInfo = ProjectConfigManager('getFileInfo', filePath)
%   success = ProjectConfigManager('openFile', filePath)

    switch lower(operation)
        case 'getconfigpath'
            % 获取项目配置目录路径
            varargout{1} = getProjectConfigPath();
            
        case 'getcategorydata' 
            % 获取按功能分类的配置文件数据
            if nargin < 2
                error('ProjectConfigManager:MissingInput', '需要提供配置目录路径');
            end
            varargout{1} = getCategoryData(varargin{1});
            
        case 'getfileinfo'
            % 获取文件详细信息
            if nargin < 2
                error('ProjectConfigManager:MissingInput', '需要提供文件路径');
            end
            varargout{1} = getFileInfo(varargin{1});
            
        case 'openfile'
            % 在MATLAB编辑器中打开文件
            if nargin < 2
                error('ProjectConfigManager:MissingInput', '需要提供文件路径');
            end
            varargout{1} = openConfigFile(varargin{1});
            
        otherwise
            error('ProjectConfigManager:UnknownOperation', '未知操作: %s', operation);
    end
end

function configPath = getProjectConfigPath()
    % 获取项目配置目录路径
    % 基于DO-178规则第2条：严禁fallback机制，直接使用ProjectPathManager
    % 基于DO-178规则第4条：架构分离原则，使用统一的路径管理接口
    
    try
        % 直接使用ProjectPathManager获取配置目录路径
        configPath = ProjectPathManager.getDirPath('project configuration root');
    catch ME
        % 符合规则第2条：不使用fallback，明确报告错误
        error('ProjectConfigManager:ConfigPathNotFound', ...
              '无法获取项目配置目录路径: %s', ME.message);
    end
end

function categoryData = getCategoryData(configPath)
    % 获取按功能分类的配置文件数据
    
    if isempty(configPath) || ~exist(configPath, 'dir')
        categoryData = [];
        return;
    end
    
    categoryData = struct();
    
    % 1. 项目结构配置
    categoryData.structure = struct();
    categoryData.structure.name = '🏗️ 工件目录配置';
    categoryData.structure.files = {'project_structure_simple.csv'};
    categoryData.structure.description = '项目目录结构定义文件';
    
    % 2. 命名规范
    categoryData.naming = struct();
    categoryData.naming.name = '📝 工件名配置';
    categoryData.naming.files = {'naming_convention_simple.csv'};
    categoryData.naming.description = '项目文件命名约定规则';
    
    % 3. 项目配置
    categoryData.config = struct();
    categoryData.config.name = '⚙️ 项目配置';
    categoryData.config.files = {'project_config.yml'};
    categoryData.config.description = '项目全局配置参数（YAML格式）';
    
    % 4. 检查规则
    categoryData.checks = struct();
    categoryData.checks.name = '🔍 检查规则';
    categoryData.checks.files = {};
    categoryData.checks.path = fullfile(configPath, 'checks');
    categoryData.checks.description = '模型和代码检查规则配置';
    
    % 扫描checks文件夹
    if exist(categoryData.checks.path, 'dir')
        checksFiles = dir(fullfile(categoryData.checks.path, '*'));
        checksFiles = checksFiles(~[checksFiles.isdir]);
        categoryData.checks.files = {checksFiles.name};
    end
    
    % 5. 模板文件
    categoryData.templates = struct();
    categoryData.templates.name = '📋 模板文件';
    categoryData.templates.files = {};
    categoryData.templates.path = fullfile(configPath, 'templates');
    categoryData.templates.description = '项目模板和配置模板';
    
    % 递归扫描templates文件夹
    if exist(categoryData.templates.path, 'dir')
        categoryData.templates.fileTree = scanDirectoryRecursive(categoryData.templates.path);
    else
        categoryData.templates.fileTree = [];
    end
end

function fileTree = scanDirectoryRecursive(dirPath)
    % 递归扫描目录，返回文件树结构
    fileTree = struct();
    fileTree.name = '';
    fileTree.path = dirPath;
    fileTree.isDir = true;
    fileTree.children = {};
    
    if ~exist(dirPath, 'dir')
        return;
    end
    
    items = dir(dirPath);
    items = items(~ismember({items.name}, {'.', '..'}));
    
    for i = 1:length(items)
        childItem = struct();
        childItem.name = items(i).name;
        childItem.path = fullfile(dirPath, items(i).name);
        childItem.isDir = items(i).isdir;
        
        if items(i).isdir
            % 递归处理子目录
            childItem.children = scanDirectoryRecursive(childItem.path).children;
        else
            childItem.children = {};
        end
        
        fileTree.children{end+1} = childItem;
    end
end

function fileInfo = getFileInfo(filePath)
    % 获取文件详细信息
    fileInfo = struct();
    
    if isempty(filePath) || ~exist(filePath, 'file')
        fileInfo.exists = false;
        fileInfo.error = '文件不存在';
        return;
    end
    
    fileInfo.exists = true;
    fileInfo.path = filePath;
    
    % 获取文件基本信息
    [pathStr, name, ext] = fileparts(filePath);
    fileInfo.name = [name ext];
    fileInfo.directory = pathStr;
    fileInfo.extension = ext;
    
    % 获取文件属性
    try
        fileDetails = dir(filePath);
        fileInfo.size = fileDetails.bytes;
        fileInfo.sizeFormatted = formatFileSize(fileDetails.bytes);
        fileInfo.dateModified = fileDetails.date;
        fileInfo.isReadOnly = ~fileDetails.datenum; % 简化的只读检查
    catch
        fileInfo.size = 0;
        fileInfo.sizeFormatted = '未知';
        fileInfo.dateModified = '';
        fileInfo.isReadOnly = false;
    end
    
    % 确定文件类型
    fileInfo.type = determineFileType(ext);
    fileInfo.category = determineFileCategory(filePath);
end

function sizeStr = formatFileSize(bytes)
    % 格式化文件大小显示
    if bytes < 1024
        sizeStr = sprintf('%d B', bytes);
    elseif bytes < 1024^2
        sizeStr = sprintf('%.1f KB', bytes/1024);
    elseif bytes < 1024^3
        sizeStr = sprintf('%.1f MB', bytes/1024^2);
    else
        sizeStr = sprintf('%.1f GB', bytes/1024^3);
    end
end

function fileType = determineFileType(extension)
    % 根据扩展名确定文件类型
    switch lower(extension)
        case {'.m'}
            fileType = 'MATLAB脚本';
        case {'.csv'}
            fileType = 'CSV数据文件';
        case {'.yml', '.yaml'}
            fileType = 'YAML配置文件';
        case {'.json'}
            fileType = 'JSON配置文件';
        case {'.xml'}
            fileType = 'XML配置文件';
        case {'.slx', '.mdl'}
            fileType = 'Simulink模型';
        case {'.sltx'}
            fileType = 'Simulink模板';
        otherwise
            fileType = '未知类型';
    end
end

function category = determineFileCategory(filePath)
    % 根据文件路径确定文件分类
    if contains(filePath, 'structure')
        category = '项目结构';
    elseif contains(filePath, 'naming')
        category = '命名规范';
    elseif contains(filePath, 'config')
        category = '项目配置';
    elseif contains(filePath, 'report') || contains(filePath, 'Report')
        category = '报告配置';
    elseif contains(filePath, 'checks')
        category = '检查规则';
    elseif contains(filePath, 'templates')
        category = '模板文件';
    else
        category = '其他';
    end
end

function success = openConfigFile(filePath)
    % 在MATLAB编辑器中打开配置文件
    success = false;
    
    if isempty(filePath) || ~exist(filePath, 'file')
        error('ProjectConfigManager:FileNotFound', '文件不存在: %s', filePath);
    end
    
    try
        open(filePath);
        success = true;
    catch ME
        error('ProjectConfigManager:OpenFileFailed', '无法打开文件 %s: %s', filePath, ME.message);
    end
end
